﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Users;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler
{
    public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userRep;

        public UpdateUserCommandHandler(IBaseRepository<User> userRep)
        {
            this.userRep = userRep;
        }
        public Task<APIResult<object>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
           


            var obj = userRep.GetAll().FirstOrDefault(x => x.UserId == request.UserId);
            
            obj.UserName=request.UserName;
            obj.NickName = request.NickName;
            obj.Sex = request.Sex;
            obj.ProvinceId = request.ProvinceId;
            obj.CityId = request.CityId;
            obj.CountyId = request.CountyId;
            obj.HamletName = request.HamletName;
            obj.UpdateName = request.UpdateName;
            obj.UpdateTime = DateTime.Now;
            var list = userRep.GetAll().Where(x=>x.UserName== request.UserName);
            if (list.Count()==0)
            {
                userRep.Update(obj);
                result.Code = APIEnum.修改成功;
                result.Msg = APIEnum.修改成功.ToString();
            }
            else
            {
                result.Code = APIEnum.用户名重复;
                result.Msg = APIEnum.用户名重复.ToString();
            }
            
            return Task.FromResult(result);
        }
    }
}
